package com.derbysoft.synxisadapter.dswitch2.service.impl;

import com.derbysoft.synxisadapter.commons.model.Role;
import com.derbysoft.synxisadapter.commons.model.User;
import com.derbysoft.synxisadapter.commons.repository.UserRepository;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.ArrayList;
import java.util.Collection;

public class UserDetailsServiceImpl implements UserDetailsService {
    private UserRepository userRepository;

    public UserDetails loadUserByUsername(String name){
        User user = userRepository.findByName(name);
        if (user == null) {
            user = new User();
            user.setName(name);
            user.setRoles(new ArrayList<Role>());
            user.setDisabled(Boolean.TRUE);
        }
        return makeUserDetails(user);
    }

    private UserDetails makeUserDetails(final User user) {
        return new UserDetails() {

            public Collection<GrantedAuthority> getAuthorities() {
                ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

                grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_COMMON"));
                for (Role role : user.getRoles()) {
                    grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_" + role.getName()));
                }
                return grantedAuthorities;
            }

            public String getPassword() {
                return null;
            }

            public String getUsername() {
                return user.getName();
            }

            public boolean isAccountNonExpired() {
                return true;
            }

            public boolean isAccountNonLocked() {
                return true;
            }

            public boolean isCredentialsNonExpired() {
                return true;
            }

            public boolean isEnabled() {
                return !user.getDisabled();
            }
        };
    }

    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}
